<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数据校验插件开发</title>
    <script src="../vue.global.js"></script>
</head>
<body>
<div id="app"></div>
<script>
    /**
     * 对数据做校验的插件
     */
    const app = Vue.createApp({
        data() {
            return {
                name:'dell',
                age:28
            }
        },
        rules:{
            age:{
                validate:(age)=>{return age > 25},
                message:'too young,too simple'
            },
            name:{
                validate:(name)=>name.length >= 4,
                message: 'name too short'
            }
        },
        methods: {},
        template: `
            <div>name:{{name}},age:{{age}}</div>
        `
    });
    const validatePlugin = {
        install(app,options){
            app.mixin({
                created(){
                    // console.log(this.$options.rules)
                    for(let key in this.$options.rules){
                        const item = this.$options.rules[key];
                        this.$watch(key,(value)=>{
                            const result = item.validate(value);
                            if(!result){
                                console.log(item.message)
                            }
                        })
                    }
                }
            })
        }
    }
    app.use(validatePlugin)
    /*app.mixin({
        created(){
            // console.log(this.$options.rules)
            for(let key in this.$options.rules){
                const item = this.$options.rules[key];
                this.$watch(key,(value)=>{
                    const result = item.validate(value);
                    if(!result){
                        console.log(item.message)
                    }
                })
            }
        }
    })*/
    const vm = app.mount("#app");
</script>
</body>
</html>